package com.atts.baccarat.table;

import java.util.ArrayList;
import java.util.List;

import com.atts.baccarat.table.util.CollectionUtil;

/**
 * 表格抽象类
 * 
 * @author Administrator
 * 
 */
public class Table {

	/**
	 * 存放表格元素
	 */
	private final List<List<TableItem>> matrix = new ArrayList<List<TableItem>>();

	/**
	 * 行数
	 */
	private final int rowCount;

	public Table(final int rowCount) {
		this.rowCount = rowCount;
	}

	/**
	 * 增加表格元素， 如果越界， 则自动增长
	 * 
	 * @param rowIndex
	 *            rowIndex
	 * @param columnIndex
	 *            columnIndex
	 * @param item
	 *            item
	 */
	public void addItem(final int rowIndex, final int columnIndex,
			final TableItem item) {

		if (columnIndex < 0 || rowIndex < 0) {
			throw new IllegalArgumentException(
			"Invalid rowIndex or columnIndex");
		}

		CollectionUtil.ensureSize(this.matrix, columnIndex);

		List<TableItem> column = this.matrix.get(columnIndex);

		if (column == null) {
			column = new ArrayList<TableItem>();
			this.matrix.set(columnIndex, column);
		}

		CollectionUtil.ensureSize(column, rowIndex);

		column.set(rowIndex, item);
	}

	/**
	 * 取得表格元素， 如果越界， 则自动增长
	 * 
	 * @param rowIndex
	 *            rowIndex
	 * @param columnIndex
	 *            columnIndex
	 * @return TableItem
	 */
	public TableItem getItem(final int rowIndex, final int columnIndex) {

		CollectionUtil.ensureSize(this.matrix, columnIndex);

		List<TableItem> column = this.matrix.get(columnIndex);

		if (column == null) {
			column = new ArrayList<TableItem>();
			this.matrix.set(columnIndex, column);
		}

		CollectionUtil.ensureSize(column, rowIndex);

		return column.get(rowIndex);
	}

	/**
	 * 清空数据
	 */
	public void clear() {

		for (final List<TableItem> column : this.matrix) {
			if (column != null) {
				column.clear();
			}
		}

		this.matrix.clear();
	}

	/**
	 * 得到所有元素
	 * 
	 * @return matrix
	 */
	public List<List<TableItem>> getMatrix() {
		return this.matrix;
	}

	/**
	 * 得到行数
	 * 
	 * @return rowCount
	 */
	public int getRowCount() {
		return this.rowCount;
	}

}
